package org.zjx.action.game.gather;

import org.zjx.analysis.window.RoleAnalysis;
import org.zjx.action.game.AbstractWindowAction;
import org.zjx.core.IWindow;
import org.zjx.state.RoleState;

import java.awt.*;
import java.awt.event.KeyEvent;

public class GatherRoleAction extends AbstractWindowAction {
    private RoleAnalysis roleAnalysis;

    public GatherRoleAction(IWindow targetWindow) {
        super(targetWindow);
    }

    private void analysis() {
        roleAnalysis = new RoleAnalysis(targetWindow, stateManager.getGameState().getScreenshot());
    }

    @Override
    public void open() {
        analysis();
        mouseAloofWindow(roleAnalysis.windowArea == null? roleAnalysis.getOriginBounds(): roleAnalysis.windowArea);
        if (roleAnalysis.isOpened()) return;
        hotkey(KeyEvent.VK_ALT, KeyEvent.VK_W);
        flush();
        open();
    }

    @Override
    public void close() {
        analysis();
        if (!roleAnalysis.isOpened()) return;
        hotkey(KeyEvent.VK_ALT, KeyEvent.VK_W);
        flush();
        close();
    }

    @Override
    public void reSetWindow() {
        if (roleAnalysis.isTransborder()) {
            drag(roleAnalysis.conversion(roleAnalysis.windowArea,roleAnalysis.getRefImageArea()), roleAnalysis.conversion(roleAnalysis.getOriginBounds(),roleAnalysis.getRefImageArea()));
            analysis();
        }
    }

    public void mouseAloofWindow(Rectangle rect) {
        if (roleAnalysis.mouseInRect(rect)) {
            Point safePoint = roleAnalysis.findLargestRemainingAreaCenter(rect);
            move(safePoint);
        }
    }

    @Override
    protected void doExecute() throws Exception {
        if (stateManager.getGameState().isGatherRole()) return;
        open();
        reSetWindow();
        RoleState roleState = new RoleState();
        stateManager.registerState(roleState);

        roleState.setLevel(roleAnalysis.getLevel());
        roleState.setVitality(roleAnalysis.getVitality());
        roleState.setMaxVitality(roleAnalysis.getMaxVitality());
        roleState.setPhysical(roleAnalysis.getPhysical());
        roleState.setMaxPhysical(roleAnalysis.getMaxPhysical());
        roleState.setPopularity(roleAnalysis.getPopularity());
        roleState.setGangContribution(roleAnalysis.getGangContribution());
        roleState.setSectContribution(roleAnalysis.getSectContribution());
        roleState.setPotential(roleAnalysis.getPotential());
        roleState.setHealth(roleAnalysis.getHealth());
        roleState.setMaxHealth(roleAnalysis.getMaxHealth());
        roleState.setMana(roleAnalysis.getMana());
        roleState.setMaxMana(roleAnalysis.getMaxMana());
        roleState.setRage(roleAnalysis.getRage());
        roleState.setMaxRage(roleAnalysis.getMaxRage());
        roleState.setInjury(roleAnalysis.getInjury());


        close();
        stateManager.getGameState().setGatherRole(true);
    }
}
